using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using OrderingSystem.Core.Entities;
using OrderingSystem.Infrastructure.Data;
using OrderingSystem.API.Models;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace OrderingSystem.API.Controllers
{
    [ApiController]
    [Route("yonghu")]
    public class AuthController : ControllerBase
    {
        private readonly ApplicationDbContext _context;
        private readonly IConfiguration _configuration;

        public AuthController(
            ApplicationDbContext context,
            IConfiguration configuration)
        {
            _context = context;
            _configuration = configuration;
        }

        [HttpPost("register")]
        public async Task<IActionResult> Register([FromBody] RegisterModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            // 检查用户名是否已存在
            if (await _context.Users.AnyAsync(u => u.yonghuming == model.Username))
            {
                return Ok(new { code = 1, msg = "用户名已存在" });
            }

            var user = new User
            {
                yonghuming = model.Username,
                mima = model.Password, // 注意：实际应用中应该对密码进行哈希处理
                xingming = model.Name,
                xingbie = model.Gender,
                lianxidianhua = model.Phone,
                touxiang = "default.png",
                addtime = DateTime.Now
                // Role和IsDeleted属性已在数据库映射中被忽略，不需要设置
            };

            _context.Users.Add(user);
            await _context.SaveChangesAsync();

            return Ok(new { code = 0, msg = "注册成功" });
        }

        [HttpPost("login")]
        public async Task<IActionResult> Login([FromBody] LoginModel model)
        {
            // 参数验证
            if (model == null)
            {
                return Ok(new { code = 1, msg = "请求数据无效" });
            }

            if (string.IsNullOrEmpty(model.Username) || string.IsNullOrEmpty(model.Password))
            {
                return Ok(new { code = 1, msg = "用户名或密码不能为空" });
            }

            // 使用AsNoTracking()优化查询性能
            var user = await _context.Users
                .AsNoTracking()
                .FirstOrDefaultAsync(u => u.yonghuming == model.Username);
                
            if (user == null)
            {
                return Ok(new { code = 1, msg = "账号或密码不正确" });
            }

            // 验证密码
            if (user.mima != model.Password) // 注意：实际应用中应该验证哈希密码
            {
                return Ok(new { code = 1, msg = "账号或密码不正确" });
            }

            // 确定用户角色
            var roles = new List<string> { "User" };
            if (model.Username.ToLower() == "admin")
            {
                roles.Add("Admin");
            }

            // 生成JWT令牌
            var token = GenerateJwtToken(user, roles);

            return Ok(new
            {
                code = 0,
                msg = "登录成功",
                token = token,
                username = user.yonghuming,
                role = "用户",
                id = user.id
            });
        }

        [HttpGet("session")]
        [Authorize]
        public async Task<IActionResult> GetUserInfo()
        {
            var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            if (string.IsNullOrEmpty(userId) || !long.TryParse(userId, out long id))
            {
                return Unauthorized();
            }

            var user = await _context.Users.FindAsync(id);
            if (user == null)
            {
                return NotFound();
            }

            return Ok(new
            {
                code = 0,
                data = user
            });
        }

        [HttpGet("resetPass")]
        public async Task<IActionResult> ResetPassword([FromQuery] string username)
        {
            if (string.IsNullOrEmpty(username))
            {
                return Ok(new { code = 1, msg = "用户名不能为空" });
            }

            var user = await _context.Users.FirstOrDefaultAsync(u => u.yonghuming == username);
            if (user == null)
            {
                return Ok(new { code = 1, msg = "用户不存在" });
            }

            // 重置密码为123456
            user.mima = "123456";
            await _context.SaveChangesAsync();

            return Ok(new { code = 0, msg = "密码已重置为123456" });
        }

        [HttpGet("page")]
        public async Task<IActionResult> GetPage([FromQuery] int page, [FromQuery] int limit, [FromQuery] string sort, 
            [FromQuery] string yonghuming = null, [FromQuery] string xingming = null)
        {
            try
            {
                // 构建查询
                var query = _context.Users.AsQueryable();

                // 应用筛选条件
                if (!string.IsNullOrEmpty(yonghuming))
                {
                    // 移除百分号以支持LIKE查询
                    yonghuming = yonghuming.Replace("%", "");
                    query = query.Where(u => EF.Functions.Like(u.yonghuming, $"%{yonghuming}%"));
                }

                if (!string.IsNullOrEmpty(xingming))
                {
                    // 移除百分号以支持LIKE查询
                    xingming = xingming.Replace("%", "");
                    query = query.Where(u => EF.Functions.Like(u.xingming, $"%{xingming}%"));
                }

                // 计算总记录数
                var total = await query.CountAsync();

                // 应用排序和分页
                var sortField = string.IsNullOrEmpty(sort) ? "id" : sort;
                var sortProperty = typeof(User).GetProperty(sortField);
                
                if (sortProperty != null)
                {
                    // 默认按ID升序排序
                    query = query.OrderBy(u => u.id);
                }

                var users = await query
                    .Skip((page - 1) * limit)
                    .Take(limit)
                    .ToListAsync();

                // 返回分页结果
                return Ok(new
                {
                    code = 0,
                    msg = "获取成功",
                    data = new
                    {
                        total,
                        list = users,
                        page,
                        limit
                    }
                });
            }
            catch (Exception ex)
            {
                return Ok(new { code = 1, msg = $"获取用户列表失败: {ex.Message}" });
            }
        }

        private string GenerateJwtToken(User user, IList<string> roles)
        {
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.NameIdentifier, user.id.ToString()),
                new Claim(ClaimTypes.Name, user.yonghuming)
            };

            foreach (var role in roles)
            {
                claims.Add(new Claim(ClaimTypes.Role, role));
            }

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JwtSettings:SecretKey"]));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var expires = DateTime.Now.AddDays(Convert.ToDouble(_configuration["JwtSettings:ExpirationDays"]));

            var token = new JwtSecurityToken(
                issuer: _configuration["JwtSettings:Issuer"],
                audience: _configuration["JwtSettings:Audience"],
                claims: claims,
                expires: expires,
                signingCredentials: creds
            );

            return new JwtSecurityTokenHandler().WriteToken(token);
        }

        public class LoginModel
        {
            public string Username { get; set; }
            public string Password { get; set; }
        }
    }
} 